import md5 from "js-md5";

((doc) => {
  let ipt = doc.querySelector("input");
  let progress = doc.querySelector("progress");
  const chunkSize = 64 * 1024; //切片大小
  let uploaded = 0; //已上传多少

  // blob转为为字符串
  const read = (file) => {
    let reader = new FileReader();
    return new Promise((resolve, reject) => {
      reader.onload = function (event) {
        const arrayBuffer = event.target.result;
        resolve(arrayBuffer);
      };
      reader.onerror = reject;
      reader.readAsBinaryString(file);
    });
  };

  ipt.addEventListener("change", async (event) => {
    let file = event.target.files[0];
    if (!file) {
      return;
    }
    ipt.value = null;
    let content = await read(file);
    let hash = md5(content);//转成hash，保证文件唯一
    let { size, name, type } = file;
    const local = localStorage.getItem(hash);
    progress.max = size;
    if (local) {
      uploaded = Number(local);
    }
    while (uploaded < size) {
      //切片大小
      const chunk = file.slice(uploaded, uploaded + chunkSize, type);
      let fd = new FormData();
      fd.append("name", name);
      fd.append("size", size);
      fd.append("type", type);
      fd.append("file", chunk);
      fd.append("offset", uploaded);
      fd.append("hash", hash);
      try {
        await axios.post("http://localhost:5454/upload", fd);
      } catch (error) {
        console.log("上传失败");
      }

      uploaded += chunkSize;
      localStorage.setItem(hash, uploaded);
      progress.value = uploaded;
    }
    console.log("上传成功");
  });
})(document);
